import os
import time
import sys

# sdk 的发布路径(拷贝framework到此路径，并发布SDK)
sdk_path = '/TJBaseLib'
sdk_name = 'TJBaseKit'
configuration = 'Release'
#'Release'
#includeSimulator = False
includeSimulator = True

# 内部参数
spec_version = '    s.version      '

# 控制台绿色打印
def greenStyle(str):
    res = '*'*20 + '\n***\n*** ' + str + '\n***\n' + '*'*20
    return print("\033[0;32m{}\033[0m".format(res))

# 控制台红色打印
def errorStyle(str):
    res = '*'*20 + '\n***\n*** ' + str + '\n***\n' + '*'*20
    return print("\033[0;31m\33[4m{}\033[0;32m".format(res))


def getSDKVersion():
    return sys.argv[1] + '.' + time.strftime("%m%d%H")


# 提交修改后的代码
def upload_git():
    # os.system('git status &')
    os.system('git add .')
    os.system('git commit -m "auto git commit:{}"'.format(time.strftime("%m:%d:%H:%M")))
    os.system('git pull')
    os.system('git push')
    greenStyle('上传本地代码成功')

  

# XCode build  
def buildSDK():
    # 清空缓存
    os.system('rm -rf ./Build/')
    greenStyle('正在编译 SDK')

    # XCode 真机编译
    result = os.system("xcodebuild -quiet -workspace Example/" + sdk_name + ".xcworkspace -scheme "+ sdk_name + "-Example -derivedDataPath ./Build/ -destination 'generic/platform=iOS' ")

    if result == 0:
        greenStyle("编译 真机SDK 成功")

    else:
        errorStyle("编译 真机SDK 失败")
        return False
        
    upload_git()

    # 合并framework，输出最终的framework到build目录
    realPath = './Build/Build/Products/'+ configuration + '-iphoneos/' + sdk_name + "/" + sdk_name + '.framework'

    if includeSimulator:
        simulatorResult = os.system("xcodebuild -quiet -workspace Example/"+ sdk_name + ".xcworkspace -scheme "+ sdk_name + "-Example -derivedDataPath ./Build/ -sdk iphonesimulator" + " ARCHS='x86_64'")
        
        if simulatorResult == 0:
            greenStyle("编译 模拟器SDK 成功")
        else:
            errorStyle("编译 模拟器SDK 失败")
            return False

        simulatorPath = './Build/Build/Products/'+ configuration + '-iphonesimulator/' + sdk_name + "/" + sdk_name + '.framework'
        lipoResult = os.system("lipo -create " + realPath + '/' + sdk_name + ' ' + simulatorPath + '/' + sdk_name + " -output " + realPath + '/' + sdk_name)

        if lipoResult == 0:
            greenStyle("合并 SDK 成功")
        else:
            errorStyle("合并 SDK 失败")
            return False 


    # 转移目录
    os.system('echo 准备移除所有缓存文件')
    os.system('rm -rf ' + '..' + sdk_path + '/' + sdk_name + '/' + sdk_name + '.framework')
    os.system('echo 开始复制文件')

    # 拷贝路径
    os.system('cp -R ' + realPath + ' ..' + sdk_path + '/' + sdk_name + '/')
    return True


# 修改发布仓库的版本号
def changeVersion():
    file_path = '..' + sdk_path + '/' + sdk_name + '.podspec'
    with open(file_path, 'r') as f:
        lines = f.readlines()
        is_modified = False
        results = []
        for line in lines:
            if line.startswith(spec_version):
                is_modified = True
                new_line = spec_version + '= "' + getSDKVersion() + '"\n'
                results.append(new_line)
            else:
                results.append(line)
        
        if not is_modified:
            errorStyle('修改version错误，退出程序')
            return False
        with open(file_path, 'w') as wf:
            wf.writelines(results)
            greenStyle('修改version成功:' + 'version -> ' + getSDKVersion())

    return True


# 发布 SDK（原理: 所有 SDK 及依赖提交到 git 仓库）
def upload_framework():
    # 切换路径
    rootPath = os.path.dirname(sys.path[0])
    os.chdir(rootPath + sdk_path)
    
    os.system('. upgrade.sh')
    greenStyle("上传成功")



# 执行工作流
def workflow():
    if len(sys.argv) <= 1:
        errorStyle('请输入版本号(eg: 2.5.6)')
        return
    if not buildSDK():
        return
    if not changeVersion():
        return

    upload_framework()
    greenStyle("Congratulations! 🎉🎉🎉")


# 入口函数
if __name__ == '__main__':
    os.system('clear')
    workflow()



